######################
#  Replication code for 'Mediating the Electoral Connection', forthcoming in the JOP
#  John Henderson and John Brooks
#  12/7/2015    
######################    

# tableIX-nokken.R
#  :: runs iv analysis to produce results for table IX using off-the-shelf bridged nokken-poole nominate scores 

rm(list=ls())
setwd('~/Dropbox/rainReplication')
                                                                                           
system("cat nominate/hou_nom_nokken.csv | awk '{print $1}' > nominate/cong.dat")  
system("cat nominate/hou_nom_nokken.csv | awk '{print $2}' > nominate/icpsr.dat")
system("cat nominate/hou_nom_nokken.csv | cut -c 43-47 > nominate/dw1.dat")

fes.type=3
non.missings=4                                                                                                      

load('nominate/icpsrPriorNextData.Rdata')  
source('prelimMain.R')   

nokken_cong=read.csv('nominate/cong.dat')[,1] 
nokken_icpsr=read.csv('nominate/icpsr.dat')[,1] 
nokken_dw1=read.csv('nominate/dw1.dat')[,1]  

# loop over cong and icpsr
nokken_ideal=array(NA,length(icpsr))
for(i in 1:length(cong)){
	ix=which(nokken_cong==cong[i] & nokken_icpsr==icpsr[i])
	if(length(ix)>0){
		nokken_ideal[i]=nokken_dw1[ix]
	}
}    

nokken_ideal[-c(full)]=NA
nokken_ideal[which(covs$d_inc==1)]=-nokken_ideal[which(covs$d_inc==1)]

vote=nokken_ideal
vote_prv=nokken_ideal[prior_obs]

main_iv1_fe=ivreg(vote~as.factor(fe_id_num)+d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose + dose_prv + vote_prv,
	~as.factor(fe_id_num)+d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose_prv + vote_prv + rain_day+rain_day_prev,
	subset=full,data=covs) 

main_iv2_fe=ivreg(vote~as.factor(fe_id_num)+d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose + dose_prv + vote_prv,
	~as.factor(fe_id_num)+d_inc+
	dist_prev + midterm + pres_party + 
	black + construction + educ + 
	minc + farmer + forborn + gvtwkr + manuf + pop + unempld + 
	urban + retail + sos + gov + comp_cq + redistricted + 
	dose_prv + vote_prv + rain_weekend+rain_weekend_prev,
	subset=full,data=covs) 
	
main_iv1_fe_sum=summary(main_iv1_fe)
main_iv2_fe_sum=summary(main_iv2_fe)

main_iv1_fe_sumcl=coeftest.cluster(covs[full,],main_iv1_fe,cluster1='as.factor(fe_id_num)')
main_iv2_fe_sumcl=coeftest.cluster(covs[full,],main_iv2_fe,cluster1='as.factor(fe_id_num)')

save(
main_iv1_fe,main_iv2_fe,
main_iv1_fe_sum,main_iv2_fe_sum,
main_iv1_fe_sumcl,main_iv2_fe_sumcl,
file=paste('robustness/tableIX_nokken-',non.missings,'_',fes.type,'.Rdata',sep=''))

# END 